//
//  VTImageView.m
//  vTeam
//
//  Created by zhang hailong on 13-4-26.
//  Copyright (c) 2013年 hailong.org. All rights reserved.
//

#import "VTImageView.h"

#import <QuartzCore/QuartzCore.h>

#import "UIView+VTDOMElement.h"

#import "VTDOMElement+Style.h"

#import "NSObject+VTValue.h"

@implementation VTImageView

@synthesize src = _src;
@synthesize source = _source;
@synthesize loading = _loading;
@synthesize defaultImage = _defaultImage;
@synthesize loaded = _loaded;
@synthesize defaultSrc = _defaultSrc;
@synthesize reuseFileURI = _reuseFileURI;
@synthesize localAsyncLoad = _localAsyncLoad;
@synthesize cornerRadius = _cornerRadius;

-(void) dealloc{
    [_src release];
    [_defaultImage release];
    [_defaultSrc release];
    [_reuseFileURI release];
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (void)setCornerRadius:(CGFloat)cornerRadius
{
    if (_cornerRadius != cornerRadius && cornerRadius > 0) {
        self.layer.cornerRadius = cornerRadius;
        [self.layer setMasksToBounds:YES];
        _cornerRadius = cornerRadius;
    }
}

-(void) setImage:(UIImage *)image{
    [self setImage:image isLocal:NO];
}

-(void) setImage:(UIImage *) image isLocal:(BOOL) isLocal{
    if(image == nil){
        if(!isLocal){
            self.loaded = YES;
        }
        [super setImage:_defaultImage];
    }
    else{
        self.loaded = YES;
        [super setImage:image];
        __block typeof(self) weakSelf = self;
        if (image && !self.isTransition) {
            CATransition *transition = [CATransition animation];
            transition.type = kCATransitionFade;
            transition.duration = 0.3;
            transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
            [weakSelf.layer addAnimation:transition forKey:nil];
        }
    }
    if((_fitHeight || _fitWidth) && self.image){
        CGSize imageSize = [self.image size];
        CGRect r = [self frame];
        
        if(_fitWidth){
            
            if(r.size.width && r.size.height && imageSize.width && imageSize.height){
                
                if(r.size.width / r.size.height != imageSize.width / imageSize.height){
                    r.size.width = imageSize.width / imageSize.height * r.size.height;
                    
                    if(_maxWidth && r.size.width > _maxWidth){
                        r.size.width = _maxWidth;
                    }
                    
                    [self setFrame:r];
                }
                
            }
            
        }
        
        if(_fitHeight){
            
            if(r.size.width && r.size.height && imageSize.width && imageSize.height){
                
                if(r.size.width / r.size.height != imageSize.width / imageSize.height){
                    
                    r.size.height = imageSize.height / imageSize.width * r.size.width;
                    
                    if(_maxHeight && r.size.height > _maxHeight){
                        r.size.height = _maxHeight;
                    }
                    
                    [self setFrame:r];
                }
                
            }
            
        }
    }
}

-(void) setDefaultImage:(UIImage *)defaultImage{
    if(_defaultImage != defaultImage){
        if([self image] == _defaultImage){
            [super setImage:nil];
        }
        [_defaultImage release];
        _defaultImage = [defaultImage retain];
        if(self.image == nil){
            [super setImage:_defaultImage];
        }
    }
}

- (BOOL)checkSrcIsInExceptionDomainList:(NSString *)src
{
    NSURL * srcURL = [NSURL URLWithString:src];
    if (srcURL) {
        NSDictionary * infoDictionary = [[NSBundle mainBundle] infoDictionary];
        if ([infoDictionary vt_dictionaryValueForKeyPath:@"NSAppTransportSecurity.NSExceptionDomains"]) {
            NSDictionary * exceptionDomains = [NSDictionary dictionaryWithDictionary:[infoDictionary vt_dictionaryValueForKeyPath:@"NSAppTransportSecurity.NSExceptionDomains"]];
            for (NSString * exceptionDomain in exceptionDomains.allKeys) {
                if ([exceptionDomain isEqualToString:srcURL.host]) {
                    return YES;
                }
            }
        }
    }
    return NO;
}

- (NSString *)srcTransformHttpToHttps:(NSString *)httpSrc
{
    if ([httpSrc hasPrefix:@"http://"]
        && ![self checkSrcIsInExceptionDomainList:httpSrc]) {
        httpSrc = [httpSrc stringByReplacingOccurrencesOfString:@"http://" withString:@"https://" options:NSCaseInsensitiveSearch range:NSMakeRange(0, @"http://".length)];
    }
    //http://s3.licaishi.sina.com.cn无证书无法请求
    if ([httpSrc hasPrefix:@"https://s3.licaishi.sina.com.cn"]) {
        httpSrc = [httpSrc stringByReplacingOccurrencesOfString:@"https://" withString:@"http://" options:NSCaseInsensitiveSearch range:NSMakeRange(0, @"https://".length)];
    }
    return httpSrc;
}

-(void) setSrc:(NSString *)src{
    src = [self srcTransformHttpToHttps:src];
    if(_src != src && ! [_src isEqualToString:src]){
        [src retain];
        [_src release];
        _src = src;
        self.loaded = NO;
        [super setImage:_defaultImage];
    }
}


-(void) setElement:(VTDOMElement *)element{
    [super setElement:element];
    
    self.clipsToBounds = YES;
    self.contentMode = UIViewContentModeScaleAspectFill;
    self.maxWidth = [element vt_floatValueForKey:@"max-width"];
    self.maxHeight = [element vt_floatValueForKey:@"max-height"];
    self.fitWidth = [element vt_booleanValueForKey:@"fit-width"];
    self.fitHeight = [element vt_booleanValueForKey:@"fit-height"];
    self.defaultSrc = [element attributeValueForKey:@"default-src"];
    self.src = [element attributeValueForKey:@"src"];
    
}


@end
